package com.uminho.calendar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;

import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.uminho.egendmeprofessional.R;
import com.uminho.objects.Appointment;

/****c* Calendar/DayDialog
 * DESCRIPTION
 * Classe responsável pelo suporte à vista do Menu Diário
 *
 ****
 */

public class DayDialog extends Dialog{
	ArrayList<Appointment> slots=null;
	ListView listView=null;
	Context context;
	GregorianCalendar day=null;
	
	public DayDialog(Context context, ArrayList<Appointment> slots, GregorianCalendar d) {
		super(context);
		day=d;
		setContentView(R.layout.day_dialog); 
		this.context=context;
		this.slots=slots;
		
		organizeAppointments(slots);
		
		initView(slots);
		
		
	}
	
	/****f* DayDialog/organizeAppointments
	 * DESCRIPTION
	 * Método executado para organizar a lista de marcações
	 * INPUTS
	 * Recebe lista de marcações
	 * RESULT
	 * Lista de marcações organizada por tempo
	 *
	 ****
	 */
	private void organizeAppointments(ArrayList<Appointment> sl) {
		ArrayList<Appointment> aux= new ArrayList<Appointment>();
		//aux.add(new Appointment(new GregorianCalendar(day.getTime().getYear(), day.getTime().getMonth(), day.getTime().getDay(), 0,0), new GregorianCalendar(day.getTime().getYear(), day.getTime().getMonth(), day.getTime().getDay(), 0,0)));
		//aux.add(new Appointment(new GregorianCalendar(day.getTime().getYear(), day.getTime().getMonth(), day.getTime().getDay(), 23,59), new GregorianCalendar(day.getTime().getYear(), day.getTime().getMonth(), day.getTime().getDay(), 23,59)));
		
		Iterator<Appointment> it = sl.iterator();
		while(it.hasNext()){
			Appointment a= it.next();
		
			if(a.getStartDate().getTime().getDay()-day.getTime().getDay()==0 &&
					a.getStartDate().getTime().getMonth()-day.getTime().getMonth()==0 &&
					a.getStartDate().getTime().getYear()-day.getTime().getYear()==0){
				
				aux.add(a);
				
			}
			
		}
		Collections.sort(aux, new Comparator(){
			 
            public int compare(Object o1, Object o2) {
            	Appointment p1 = (Appointment) o1;
            	Appointment p2 = (Appointment) o2;
               return p1.getStartDate().getTime().compareTo(p2.getStartDate().getTime());
            }
 
        });
		
		slots=aux;
		this.slots=aux;
		
	}
	
	/****f* DayDialog/initView
	 * DESCRIPTION
	 * Método executado para inicializar a vista DayDialog
	 * INPUTS
	 * Recebe uma lista de marcações
	 * RESULT
	 * Vista iniciada
	 *
	 ****
	 */
	private void initView(ArrayList<Appointment> sl) {
		listView = (ListView) findViewById(R.id.day_dialog_list);
		ItemsAdapter itemsAdapter = new ItemsAdapter(context, slots);
		listView.setAdapter(itemsAdapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
    
            	// toast = Toast.makeText(context, "Pos: "+position+" Service id: "+id, 3000);
				//toast.show();
				
				
				Appointment a=slots.get(position);
				
				AppointmentDialog  dialog = new AppointmentDialog(context, a);
				
				SimpleDateFormat dateFormat = new SimpleDateFormat("d MMMM, yyyy");
				dialog.setTitle(dateFormat.format(a.getStartDate().getTime()));	
				dialog.show();
				DayDialog.this.dismiss();
            }
        });
		
	}

	/****c* Calendar/ItemsAdapter
	 * DESCRIPTION
	 * Classe responsável pela construção da lista de marcações
	 *
	 ****
	 */
	private class ItemsAdapter extends BaseAdapter {
		ArrayList<Appointment> slots=null;
		SimpleDateFormat dateFormat;

		public ItemsAdapter(Context context, ArrayList<Appointment> slots) {
			this.slots=slots;
			dateFormat = new SimpleDateFormat("HH:mm");
		}

		public View getView(final int position, View convertView,
			ViewGroup parent) {
			View view = convertView;
			ImageView appoitmentIcon;
			TextView init, end, description, comment;
			Appointment slot = slots.get(position);
			
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.day_dialog_row, null);
				
			appoitmentIcon = (ImageView) view.findViewById(R.layout.day_dialog_row);
			
			Date initDate = slot.getStartDate().getTime();
			init = (TextView) view.findViewById(R.id.init_hour_textView);
			init.setText(dateFormat.format(initDate)+" - ");
			
			Date endDate = slot.getEndDate().getTime();
			end = (TextView) view.findViewById(R.id.end_hour_textView);
			end.setText(dateFormat.format(endDate));
			
			description = (TextView) view.findViewById(R.id.hour_description_textView);
			comment = (TextView) view.findViewById(R.id.hour_comment_textView);
			try{
				description.setText(slot.getService().getTitle()/*+"\n\n"+slot.getStartDate().getTime().toString()+"\n"+slot.getEndDate().getTime().toString()*/);
				
				comment.setText(slot.getComment());
			}catch (Exception e){
				Log.d("Day Adapter exc", e.toString());
				
			}
			
			
			}
				
			return view;
		}

		public int getCount() {
			return slots.size();
		}

		public Object getItem(int position) {
			return slots.get(position);
		}

		public long getItemId(int position) {
			return slots.get(position).getService().getServiceId();
		}
	}
	public void setDayDate(GregorianCalendar d){
		this.day=d;
	}

}
